package com.foxzzz.datamemory.util;

import org.springframework.http.RequestEntity;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

/**
 * @Author wujie
 * @Class TestApi
 * @Description
 * @Date 2020/7/15 8:22
 */
public class HttpSendUtil {
    private final static String BASE="https://www.yuque.com/api/v2";
    private static RestTemplate restTemplate = new RestTemplate();
    private  static String TOKEN=null;

    public static void setToken(String token){
        TOKEN=token;
    }
    public static String get(String url) {
        url = BASE + url;
        RequestEntity requestEntity = null;
        try {
            requestEntity = RequestEntity.get(new URI(url)).header("X-Auth-Token",TOKEN).build();
            return restTemplate.exchange(requestEntity, String.class).getBody();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String delete(String url) {
        url = BASE + url;
        RequestEntity requestEntity = null;
        try {
            requestEntity = RequestEntity.delete(new URI(url)).header("X-Auth-Token",TOKEN).build();
            return restTemplate.exchange(requestEntity, String.class).getBody();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String post(String url,Map<String,String> map) {
        url = BASE + url;
        RequestEntity requestEntity = null;
        try {
            requestEntity = RequestEntity.post(new URI(url)).header("X-Auth-Token",TOKEN)
                    .header("Content-Type", "application/json")
                    .body(map);
            return restTemplate.exchange(requestEntity, String.class).getBody();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String put(String url,Map<String,String> map) {
        url = BASE + url;
        RequestEntity requestEntity = null;
        try {
            requestEntity = RequestEntity.put(new URI(url)).header("X-Auth-Token",TOKEN)
                    .header("Content-Type", "application/json")
                    .body(map);
            return restTemplate.exchange(requestEntity, String.class).getBody();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }
}
